import { defineStore } from "pinia";
import { ref } from "vue";
import { loginByPhone, passwordLogin, loginByMail, getLoginUserInfo } from "@/api/user";
import type { LoginByPhoneParams, LoginByPhoneRes, LoginByAppParams, UserInfo } from "@/types/user";
import router from "@/router";
import { ElMessage } from "element-plus";

type UserStoreState = {
  token: string;
  data: Partial<UserInfo>;
};

const useUserStore = defineStore(
  "user",
  () => {
    const userInfo = ref<UserStoreState>({
      token: "",
      data: {},
    });

    const loginByEmail = async (userData: any) => {
      let res: LoginByPhoneRes = await loginByMail(userData);
      if (res.data.code === 200) {
        userInfo.value.token = res.data.data.token;
      }
      return res;
    };
    const login = async (userData: LoginByPhoneParams) => {
      let res: LoginByPhoneRes = await loginByPhone(userData);
      if (res.data.code === 200) {
        userInfo.value.token = res.data.data.token;
      }
      return res;
    };
    const pswLogin = async (userData: LoginByAppParams) => {
      let res: LoginByPhoneRes = await passwordLogin(userData);
      if (res.data.code === 200) {
        userInfo.value.token = res.data.data.token;
      }
      return res;
    };
    const getUserInfo = async () => {
      const res = await getLoginUserInfo();
      userInfo.value.data = res.data.data;
    };
    const logout = () => {
      userInfo.value.data = {}
      userInfo.value.token = ""
      router.push("/login")
      ElMessage.success("操作成功")
    }

    return {
      userInfo,
      pswLogin,
      login,
      loginByEmail,
      getUserInfo,
      logout
    };
  },
  { persist: true }
);

export default useUserStore;
